#include"udp_client.hpp"
#include"error.hpp"
#include<strings.h>
#include <string.h>
#include <sys/types.h>       
#include <sys/socket.h>
#include <stdio.h>
#include<iostream>
#include <arpa/inet.h>
// using namespace udp_client;
//./client 服务端ip + port
void usage(const std::string proc)
{
    std::cout<<"Usage "<<proc<<" severip serverport"<<std::endl;
}
void* recv(void* arg)
{
     //收消息 
    while(true)
    {
        int socket_ = *((int*)arg);
        struct sockaddr_in tmp;
        char buffer[1024] = {0};
        socklen_t len = sizeof(tmp);
        int ret = recvfrom(socket_,buffer,sizeof(buffer)-1,0,(sockaddr*)&tmp,&len);
        buffer[ret] = '\0';
        if(ret)
            std::cout<<buffer<<std::endl;
    }
    
}
int main(int argc,char*argv[])
{
    if(argc != 3)
    {
        usage(argv[0]);
        std::cout<<"stage error"<<strerror(errno)<<std::endl;
        exit(USAGE_ERR);
    }
    const std::string ip_ = argv[1];
    u_int16_t port = atoi(argv[2]);
    
    int socket_ = socket(AF_INET,SOCK_DGRAM,0);
    if(socket_ < 0)
    {
        std::cout<<"create socket error"<<strerror(errno)<<std::endl;
        exit(SOCKET_ERR);
    }
    std::cout<<"create socket successs"<<std::endl;        
    //打开网络文件
           
    //不用客户端自己绑定端口号和ip地址
    //发消息
    struct sockaddr_in sock;
    sock.sin_addr.s_addr = inet_addr(ip_.c_str());//将字符串类型的地址转为四字节地址,而且是网络字节序了
    sock.sin_port = htons(port);
    sock.sin_family = AF_INET;
    pthread_t id;
    pthread_create(&id,nullptr,recv,&socket_);
    while(true)
    {
        std::string msg;
        std::cout<<"客户端# "<<std::endl;
        getline(std::cin,msg);
        sendto(socket_,msg.c_str(),msg.size(),0,(sockaddr*)&sock,sizeof(sock));
    }   
    return 0;
}